package com.symaster.common.swing.dialog;

import javax.swing.*;
import java.io.File;

/**
 * @author yinmiao
 * @date 2021-07-31 09:13
 */
public class SelectFileDialog {

    // 设置过滤 {{".tif", "tif图片"}, {".jpg", "jpg图片"}}
    private String[][] fileNames = {{".plf", "plf排版清单"}};
    // 默认目录
    private String defaultFilePath = "D:\\系统生成排版文件\\2021-07-31";

    public static void main(String[] args) {
        SelectFileDialog selectFileDialog = new SelectFileDialog();
        File open = selectFileDialog.open();
        System.out.println("open = " + open);
    }

    public File open() {
        JFileChooser jf = defaultFilePath == null ? new JFileChooser() : new JFileChooser(this.defaultFilePath);
        fileFilter(jf);
        jf.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        if (fileNames != null && fileNames.length > 0) {
            jf.setSelectedFile(new File(this.defaultFilePath + File.separator + "*" + this.fileNames[0][0]));
        }
        jf.showOpenDialog(null);
        File selectedFile = jf.getSelectedFile();
        if (selectedFile.isDirectory()) {
            return selectedFile;
        }
        if (selectedFile.isFile()) {
            return selectedFile;
        }
        for (int i = 0; i < fileNames.length; i++) {
            String[] fileName = fileNames[i];
            File tempFile = new File(selectedFile + fileName[0]);
            if (tempFile.isFile()) {
                return tempFile;
            }
        }
        return null;
    }

    private void fileFilter(JFileChooser F) {

        if (this.fileNames == null || this.fileNames.length <= 0) {
            return;
        }
        // 循环添加需要显示的文件
        for (final String[] fileEName : this.fileNames) {
            F.setFileFilter(new javax.swing.filechooser.FileFilter() {
                public boolean accept(File file) {
                    return file.getName().endsWith(fileEName[0]) || file.isDirectory();
                }

                public String getDescription() {
                    return fileEName[1];
                }
            });
        }
    }

    public void setFileNames(String[][] fileNames) {
        this.fileNames = fileNames;
    }

    public void setDefaultFilePath(String defaultFilePath) {
        this.defaultFilePath = defaultFilePath;
    }
}
